const server = 'https://webinar-server.growthschool.io'; // const elems = `
👇 Choose your Slot 👇
`; const divContainer = document.createElement('div'); divContainer.innerHTML = elems; document.body.appendChild(divContainer); const webinarPopup = document.querySelector('.webinar-popup'); const popupBackdrop = document.querySelector('.webinar-popup-backdrop'); const closeButton = webinarPopup.querySelector('.webinar-close-button'); const seeSlotsButton = webinarPopup.querySelector('#webinar-see-slots'); const nextSessionButton = document.createElement('button'); const nextDayButton = document.createElement('button'); nextSessionButton.classList.add('webinar-button'); nextDayButton.classList.add('webinar-button'); const loaderElement = document.createElement('div'); loaderElement.innerHTML = `
`; nextDayButton.style.marginTop = '16px'; const urlSearchParams = new URLSearchParams(window.location.search); const params = Object.fromEntries(urlSearchParams.entries()); console.log(params); let webinarId = params.id ? +params.id : 1; function openWebinarPopup(id) { if (id !== undefined) { webinarId = id; } webinarPopup.style.display = 'block'; popupBackdrop.style.display = 'block'; updateSlotsAndButtons(); setTimeout(() => { webinarPopup.style.opacity = 1; popupBackdrop.style.opacity = 1; }); } function closeWebinarPopup() { webinarPopup.style.opacity = 0; popupBackdrop.style.opacity = 0; setTimeout(() => { webinarPopup.style.display = 'none'; popupBackdrop.style.display = 'none'; }, 300); } popupBackdrop.addEventListener('click', closeWebinarPopup); closeButton.addEventListener('click', () => { closeWebinarPopup(); }); const millisecondsInOne = { second: 1000, minute: 60 * 1000, hour: 60 * 60 * 1000, day: 24 * 60 * 60 * 1000, }; const getTimeDifference = (futureDate) => { const currentDate = new Date(); let timeDiff = futureDate.getTime() - currentDate.getTime(); if (timeDiff < 0) return; const days = Math.floor(timeDiff / millisecondsInOne.day); timeDiff -= days * millisecondsInOne.day; const hours = Math.floor(timeDiff / millisecondsInOne.hour); timeDiff -= hours * millisecondsInOne.hour; const minutes = Math.floor(timeDiff / millisecondsInOne.minute); timeDiff -= minutes * millisecondsInOne.minute; const seconds = Math.floor(timeDiff / millisecondsInOne.second); return { days, hours, minutes, seconds }; }; const getFormattedTimer = (futureDate) => { const values = getTimeDifference(futureDate); if (!values) return '00:00:00'; const { days, hours, minutes, seconds } = values; let timerString = ''; if (days) { timerString += String(days).padStart(2, '0'); timerString += ':'; } if (hours) { timerString += String(hours).padStart(2, '0'); timerString += ':'; } // to alway show minutes if (true) { timerString += String(minutes).padStart(2, '0'); timerString += ':'; } // to always get seconds as 00 if (true) { timerString += String(seconds).padStart(2, '0'); } return timerString; }; function formatAMPM(date) { var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'PM' : 'AM'; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; } const getWebinarSchedules = async () => { const prevDateAtSameTime = new Date(); prevDateAtSameTime.setDate(prevDateAtSameTime.getDate() - 1); // TODO: we can change things here need to decide const threeDaysLaterAtSameTime = new Date(); threeDaysLaterAtSameTime.setDate(threeDaysLaterAtSameTime.getDate() + 3); try { const webinarSchedules = await fetch( `${server}/webinarSchedules?webinarId=${webinarId}&_sort=startTime&_order=asc&startTime_gte=${prevDateAtSameTime.toISOString()}&startTime_lte=${threeDaysLaterAtSameTime.toISOString()}` ).then((res) => res.json()); return webinarSchedules; } catch (err) { console.error(err); return []; } }; const MINUTES_TILL_USER_CAN_JOIN_LATE_SESSION = 2; (async () => { const webinarSchedules = await getWebinarSchedules(); console.log( webinarSchedules.map((s) => { return { ...s, startTime: new Date(s.startTime).toLocaleString(), }; }) ); if (webinarSchedules.length === 0) { seeSlotsButton.innerHTML = 'No Schedules'; } else { seeSlotsButton.innerHTML = 'See the Slots'; seeSlotsButton.addEventListener('click', async () => { seeSlotsButton.style.display = 'none'; webinarPopup.appendChild(loaderElement); webinarPopup.appendChild(nextSessionButton); webinarPopup.appendChild(nextDayButton); updateSlotsAndButtons(); }); } })(); const updateSlotsAndButtons = async () => { loaderElement.style.display = 'block'; nextSessionButton.style.display = 'none'; nextDayButton.style.display = 'none'; const webinarSchedules = await getWebinarSchedules(); if (webinarSchedules.length === 0) return; const associatedWebinar = await fetch(`${server}/webinars/${webinarId}`).then( (res) => res.json() ); // after both await calls we can remove loaderElement loaderElement.style.display = 'none'; let i = 0; const currentDate = new Date(); while ( i < webinarSchedules.length && new Date(webinarSchedules[i].startTime) < currentDate ) { i++; } let recentSession; if (i > 0) { const previousSession = webinarSchedules[i - 1]; const previousSessionDate = new Date(previousSession.startTime); const previousSessionEndDate = new Date( previousSessionDate.getTime() + associatedWebinar.duration ); const notLateBeyondCertainMinutes = currentDate.getTime() - previousSessionDate.getTime() < MINUTES_TILL_USER_CAN_JOIN_LATE_SESSION * millisecondsInOne.minute; const notEnded = currentDate < previousSessionEndDate; if (notEnded && notLateBeyondCertainMinutes) { // less than 5 minutes passed since session started and previous session has not ended yet so we // can let user enter this session only recentSession = previousSession; nextSessionButton.innerHTML = 'Join Session in progress'; } } if (!recentSession) { // otherwise let user enter into closest next session if (i < webinarSchedules.length) { recentSession = webinarSchedules[i]; const sessionDate = new Date(recentSession.startTime); let updateInterval; function updateTimer() { let timerString = getFormattedTimer(sessionDate); if (timerString === '00:00:00') { nextSessionButton.innerHTML = `Join Session in progress`; clearInterval(updateInterval); return; } nextSessionButton.innerHTML = `Starting in ${timerString}`; } updateTimer(); updateInterval = setInterval(updateTimer, 1000); } else { nextSessionButton.innerHTML = 'No schedule'; } } if (recentSession) { nextSessionButton.addEventListener('click', async () => { const signupResult = await signupUser(recentSession.id); if (signupResult) { location.href = `https://webinar.growthschool.io/live?webinarScheduleId=${recentSession.id}&webinarSignupId=${signupResult.id}`; } else { alert('Please enter correct credentials'); } }); } const nextDateAtSameTime = new Date(); nextDateAtSameTime.setDate(nextDateAtSameTime.getDate() + 1); i = 0; while ( i < webinarSchedules.length && new Date(webinarSchedules[i].startTime) <= nextDateAtSameTime ) { i++; } let nextDaySession; if (i < webinarSchedules.length) { nextDayButton.innerHTML = `Tomorrow at ${formatAMPM( new Date(webinarSchedules[i].startTime) )} (IST)`; nextDayButton.style.display = 'block'; nextDaySession = webinarSchedules[i]; nextDayButton.addEventListener('click', async () => { const signupResult = await signupUser(nextDaySession.id); if (signupResult) { alert( 'Your slot is booked Please come back ' + `Tomorrow at ${formatAMPM( new Date(webinarSchedules[i].startTime) )} (IST)` ); } else { alert('Please enter correct credentials'); } }); } else { nextDayButton.style.display = 'none'; } nextSessionButton.style.display = 'block'; }; const signupUser = async (webinarScheduleId) => { const inputsContainer = webinarPopup.querySelector( '.webinar-inputs-container' ); const nameInput = inputsContainer.querySelector('#webinar-name-input'); const emailInput = inputsContainer.querySelector('#webinar-email-input'); const phoneInput = inputsContainer.querySelector('#webinar-phone-input'); const name = nameInput.value; const email = emailInput.value; const phone = phoneInput.value; const emailCheck = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i; let modifiedPhone = phone.replaceAll(' ', ''); if (modifiedPhone.startsWith('+91')) { modifiedPhone = modifiedPhone.slice(3, modifiedPhone.length); } if (modifiedPhone.startsWith('0')) { modifiedPhone = modifiedPhone.slice(1, modifiedPhone.length); } const nameValid = name !== ''; const emailValid = emailCheck.test(email); const phoneValid = modifiedPhone.match(/\D+/g) === null && modifiedPhone.length === 10; if (!nameValid || !emailValid || !phoneValid) { return false; } const payload = { name, email, phone: modifiedPhone, webinarId: webinarId, webinarScheduleId: webinarScheduleId, }; const response = await fetch(`${server}/webinarSignups`, { method: 'POST', body: JSON.stringify(payload), headers: { 'content-type': 'application/json', }, }); const data = await response.json(); console.log(data); return data; };